<template>
  <div id="app">
    <el-form :inline="true" :model="formSelect" class="demo-form-inline">
      <el-form-item label="姓名" prop="stuName">
        <el-autocomplete
          size="small"
          clearable
          class="inline-input"
          v-model="formSelect.stuName"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入学生姓名"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="开始日期" prop="startTime">
        <el-date-picker
          size="small"
          v-model="formSelect.startTime"
          value-format=" yyyy-MM-dd"
          format="yyyy-MM-dd"
          type="date"
          placeholder="开始日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="结束日期" prop="endTime">
        <el-date-picker
          size="small"
          v-model="formSelect.endTime"
          value-format=" yyyy-MM-dd"
          format="yyyy-MM-dd"
          type="date"
          placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button
          size="small"
          @click="getDataList()"
          type="primary"
          icon="el-icon-search"
          >查询</el-button
        >
        <el-button size="small" type="success" @click="add()">新增</el-button>
        <el-button size="small" type="danger" @click="deleteHandle()"
          >批量删除</el-button
        >
        <el-button size="small" @click="uploadExcel" type="primary">
          <input type="file" name id="file" style="display: none" />
          导入Excel
        </el-button>
        <el-button size="small" type="success" @click="download"
          >导出Excel</el-button
        >
        <el-button size="small" type="success" @click="shuttering"
          >下载模板</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%"
    >
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50"
      ></el-table-column>
      <el-table-column
        prop="stuNumber"
        header-align="center"
        align="center"
        label="学号"
      ></el-table-column>
      <el-table-column
        prop="name"
        header-align="center"
        align="center"
        label="姓名"
      ></el-table-column>
      <el-table-column
        prop="collegeName"
        header-align="center"
        align="center"
        label="学院"
      ></el-table-column>
      <el-table-column
        prop="stuclass"
        header-align="center"
        align="center"
        label="班级"
      ></el-table-column>
      <el-table-column
        prop="dormName"
        header-align="center"
        align="center"
        label="寝室"
      ></el-table-column>
      <el-table-column
        prop="date"
        header-align="center"
        align="center"
        label="晚归日期"
      ></el-table-column>
      <el-table-column
        prop="backTime"
        header-align="center"
        align="center"
        label="晚归时间"
      ></el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        label="操作"
        fixed="right"
        width="200px"
      >
        <template slot-scope="scope">
          <el-button type="success" size="small" @click="write(scope.row)"
            >修改</el-button
          >
          <el-button
            type="danger"
            size="small"
            @click="deleteHandle(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="pagination"
      background
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
    <!-- 修改页面-->
    <el-drawer
      title="填写结果"
      :visible.sync="drawer"
      direction="rtl"
      size="40%"
      ref="drawer"
    >
      <div class="demo-drawer__content">
        <el-form :model="addform" label-position="right">
          <el-form-item label="学生姓名" label-width="120px">
            <el-autocomplete
              clearable
              class="inline-input"
              :disabled="disabled"
              v-model="addform.stuName"
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入学生姓名"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="学生学号" label-width="120px">
            <!--            <el-input v-model="editForm.permissionName" />-->
            <el-input
              v-model="addform.stuNumber"
              align="right"
              :disabled="disabled"
              placeholder="学生学号"
              style="width: 220px"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="晚归日期" prop="date" label-width="120px">
            <el-date-picker
              v-model="addform.backTime"
              type="datetime"
              placeholder="选择日期时间"
              default-time="12:00:00"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item style="margin-left: 55px; margin-right: 60px">
            <el-button size="small" @click="cancelForm">取 消</el-button>
            <el-button
              size="small"
              type="primary"
              v-show="!disabled"
              @click="addDutyData"
              >提 交</el-button
            >
            <el-button
              size="small"
              type="primary"
              plain
              v-show="disabled"
              @click="upDataDutyData"
              >修改</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  getReturnList,
  getWeekList,
  getTermList,
  addDutyDetails,
  updataDutyDetails,
  deleteDutyDetails,
  excel,
  addExceldata,
  getExcel,
  downloadWorkShuttering,
} from '../../api/src/ReturnManage/ReturnManage'
import { getTeacherListByLikeName } from '../../api/src/check/a7sCheck'
import { getStudentListByLikeName } from '../../api/src/SpotCheckPlan/SpotCheckPlan'

export default {
  name: '',
  data() {
    return {
      formSelect: {
        startTime: '',
        endTime: '',
        stuName: '',
        name: '',
        class: '',
        Date: '',
        backTime: '',
        termName: '',
        teacherName: '',
        buildingName: '',
        remark: '',
        instructorName: '',
        leaderName: '',
        middleName: '',
        term: '',
        week: '',
        id: '',
      },
      form: {
        startTime: '',
        endTime: '',
        stuName: '',
        stuNumber: '',
        name: '',
        class: '',
        date: '',
        backTime: '',
        termName: '',
        teacherName: '',
        buildingName: '',
        remark: '',
        time: '',
      },
      addform: {
        stuName: '',
        stuNumber: '',
        backTime: '',
        id: '',
      },
      teamData: [],
      weekData: [],
      drawer: false,
      dataList: [],
      pageIndex: 1,
      startTime: '',
      endTime: '',
      stuName: '',
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      dynamicTags: [],
      commitType: true,
      id: '',
      excelData: [],
      disabled: false,
    }
  },
  created() {
    this.getDataList()
  },
  methods: {
    // 导入Excel数据
    uploadExcel() {
      const file = document.getElementById('file')
      file.click()
      file.onchange = () => {
        if (!this.checkType(file.files[0])) {
          this.$message.error(
            '文件：' + file.files[0].name + ' 文件类型错误，请使用Excel文件'
          )
          return false
        }
        excel(file.files[0]).then((res) => {
          if (!res) {
            this.$message.error('Excel内容格式错误！请使用正确格式。')
          }
          this.processExceldata(res)
        })
      }
    },
    // 检测文件类型
    checkType(file) {
      const fileExt = file.name.split('.').pop().toLocaleLowerCase()
      const extArr = ['xlsx', 'xls', 'csv']
      return extArr.includes(fileExt)
    },
    // 格式Excel数据
    processExceldata(data) {
      for (let index = 0; index < data.length; index++) {
        const ele = data[index]

        const celldata = {
          stuName: ele.学生姓名,
          stuNumber: ele.学生学号,
          backTime: ele.晚归时间,
        }
        this.excelData.push(celldata)
      }
      console.log(this.excelData)
      addExceldata(this.excelData).then((res) => {
        this.excelData = []
        this.getDataList()
      })
    },
    // 导出Excel数据
    download() {
      getExcel()
    },
    //导出模板
    shuttering() {
      downloadWorkShuttering()
    },
    // 获取数据列表
    async getDataList() {
      this.dataListLoading = true
      this.dataList = []
      console.log(this.formSelect.endTime + '11111')
      let parameter

      parameter =
        '?currentPage=' + this.pageIndex + '&pageSize=' + this.pageSize
      if (this.formSelect.startTime == null) {
        this.formSelect.startTime = ''
      }
      if (this.formSelect.stuName == null) {
        this.formSelect.stuName = ''
      }
      if (this.formSelect.endTime == null) {
        this.formSelect.endTime = ''
      }
      if (this.formSelect.stuName.length > 0) {
        parameter += '&stuName=' + this.formSelect.stuName
      }
      if (this.formSelect.startTime.length > 0) {
        parameter +=
          '&startTime=' + this.formSelect.startTime.replace(/-/g, '/').trim()
      }
      if (this.formSelect.endTime.length > 0) {
        parameter +=
          '&endTime=' + this.formSelect.endTime.replace(/-/g, '/').trim()
      }
      console.log('选择条件为====================》》》》》', parameter)

      await getReturnList(parameter).then((res) => {
        console.log('roleManagement::::::::>>>>', res)
        if (res.records === 0) {
          this.dataList = []
          this.totalPage = 0
        } else {
          this.dataList = res.records
          this.totalPage = res.total
        }

        this.dataListLoading = false
      })

      getTermList().then((res) => {
        this.teamData = res
      })
    },

    //
    async addDutyData() {
      console.log('========================>>>>>>>>>>>>>..数据为', this.addform)
      await addDutyDetails(
        this.addform.stuName,
        this.addform.stuNumber,
        this.addform.backTime
      ).then((res) => {
        console.log('提交成功======>>>>>>>>>>>>>>>>>>..', res)
      })
      this.addform.stuName = ''
      this.addform.stuNumber = ''
      this.addform.backTime = ''
      setTimeout(this.getDataList(), 800)
      this.$message.success('新增完成')
      this.drawer = false
    },

    async upDataDutyData() {
      this.disabled = true
      const data = await updataDutyDetails(
        this.addform.id,
        this.addform.backTime
      ).then((res) => {
        this.$message.success('更新成功')
      })

      setTimeout(this.getDataList(), 800)
      this.drawer = false
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },

    // 教师查找
    querySearchAsync(queryString, callback) {
      var list = [{}]
      var restaurants = this.restaurants

      getStudentListByLikeName(queryString).then((res) => {
        //在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示
        for (let i of res) {
          i.value = i.userName //将想要展示的数据作为value
        }
        list = res
        callback(list)
      })
    },

    handleSelect(item) {
      console.log('输入老师的名字是============================>>>>>', item)

      this.inputValue = ''
      this.dynamicTags.push(item)
      console.log('输入老师的名字列表为===============>>>>>', this.dynamicTags)
    },
    write(row) {
      this.addform.stuNumber = ''
      this.addform.stuName = ''
      this.addform.backTime = ''
      this.addform.id = ''
      this.disabled = true
      var newDate = new Date(row.date + ' ' + row.backTime)
      console.log(newDate + 'kkk')
      if (row != null) {
        this.addform.stuNumber = row.stuNumber
        this.addform.stuName = row.name
        this.addform.backTime = newDate
        this.addform.id = row.id
      } else {
        this.stuNumber = ''
      }

      this.drawer = true
    },

    add() {
      this.disabled = false
      this.addform.stuName = ''
      this.addform.stuNumber = ''
      this.addform.backTime = ''
      this.drawer = true
    },

    cancelForm() {
      this.drawer = false
    },

    // 删除
    async deleteHandle(id) {
      console.log('删除deid1111的类型', typeof id)
      var ids = id
        ? [id]
        : this.dataListSelections.map((item) => {
            return item.id
          })

      ids.push(id)
      console.log('删除deidssss', ids)
      await this.$confirm(
        `确定进行[${id ? '删除' : '批量删除'}]操作?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          console.log('删除deid', ids)
          deleteDutyDetails(ids).then((res) => {
            this.$message({
              message: '删除成功!',
              duration: 1500,
              type: 'success',
            })
          })
        })
        .catch(() => {})
      this.dataListSelections = []
      setTimeout(this.getDataList, 800)
    },
  },
}
</script>

<style>
.el-pagination {
  display: flex;
  white-space: nowrap;
  padding: 20px 5px;
  color: #303133;
}
</style>
